package android.rockchip.update.download;

import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.rockchip.update.RomUpdate;
import android.rockchip.update.service.R;
import android.rockchip.update.utils.Constants;
import android.rockchip.update.utils.Preferences;
import android.rockchip.update.utils.Utils;
import android.util.Log;

import java.io.File;

public class DownloadRom implements Constants {

    public final static String TAG = "DownloadRomUpdate";

    public DownloadRom() {

    }

    public void startDownload(Context context) {
        Log.e("DownloadRom", "开始下载");
        String url = RomUpdate.getRomUrl(context);
        String fileName = RomUpdate.getFilename(context);
        String description = context.getResources().getString(R.string.downloading);
        File file = RomUpdate.getFullFile(context);

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

        request.setTitle(fileName);
        request.setDescription(description);
        request.setVisibleInDownloadsUi(true);
        request.setDestinationInExternalPublicDir(OTA_DOWNLOAD_DIR, fileName);

        // Delete any existing files
        Utils.deleteFile(file);

        // Enqueue the download
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        long mDownloadID = downloadManager.enqueue(request);

        // Store the download ID
        Preferences.setDownloadID(context, mDownloadID);

        // Set a setting indicating the download is now running
        Preferences.setIsDownloadRunning(context, true);

        // Start updating the progress
        new DownloadRomProgress(context, downloadManager).execute(mDownloadID);

        // MD5 checker has not been run, nor passed
        Preferences.setMD5Passed(context, false);
        Preferences.setHasMD5Run(context, false);
    }

    public void cancelDownload(Context context) {
        // Grab the download ID from settings
        long mDownloadID = Preferences.getDownloadID(context);

        // Remove the download
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadManager.remove(mDownloadID);

        // Indicate that the download is no longer running
        Preferences.setIsDownloadRunning(context, false);
    }

}
